package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录成功之后，后续每一次请求都会携带token。我们规定好 token存放在请求头中，而且key是固定的：access_token
        // 因此，我们获取token，就是 从请求头中获取key为access_token的值

        System.out.println("拦截...............");

        String token = request.getHeader("access_token");
        if(!StringUtils.hasLength(token)){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        // 解析token，得到userId和username，然后封装成 LoginUser ， 保存到ThreadLocal中
        // 这样，在同一个“生产线”上的其他组件就可以从ThreadLocal中获取LoginUser了
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUser loginUser = new LoginUser(userId,username);
        LoginUserContext.setLoginUser(loginUser);


        return true ;
    }
}
